/**
 * 开单页-结算信息区
 */
import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import { Button, Divider, FormInstance, Badge, Row, Col } from 'antd';
import ProForm, { ProFormCheckbox, ProFormDatePicker, ProFormDependency, ProFormDigit, ProFormSelect, ProFormSwitch, ProFormText } from '@ant-design/pro-form';
import { useModel } from 'umi';
import { isNull } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import { getSurveyList } from '@/services/patient/followUpApi';
import { isMobile } from 'react-device-detect';
import moment from 'moment';

interface SettlementInfoProps {
  onFinish: (values: any, type: string) => void;
  onSave: (values: any, type: string, noBack?: string) => void;
  goodsList: STOCKGOODSAPI.GoodsItem[];
  settleInfo: any;
  isPay?: Boolean;
  type?: string;
  levelInfo?: { discount: number, rank?: number, integral?: number };
}

const SettlementInfo: React.FC<SettlementInfoProps> = forwardRef((props, ref) => {
  const { onFinish, onSave, goodsList = [], settleInfo = null, isPay, type, levelInfo } = props;
  const { initialState } = useModel('@@initialState');
  const formRef = useRef<FormInstance>();

  const [count, setCount] = useState(0);

  // 商品原价
  const [goodsTotalPrice, setGoodsTotalPrice] = useState<number>(0);

  // 商品折扣
  const [goodsDisaccountPrice, setGoodsDisaccountPrice] = useState<number>(0);

  // 商品数量
  const [goodsNum, setGoodsNum] = useState<number>(0);
  // 随访表信息
  const [followUpOptions, setFollowUpOptions] = useState<any[]>();
  const [surveyReadonly, setSurveyReadonly] = useState<boolean>(false);

  useEffect(() => {
    // 获取随访表列表
    getSurveyList({ current: 1, pageSize: 99 }).then(res => {
      const options = res.record_list.map(({ survey_id, survey_title }) => ({
        value: survey_id, label: survey_title
      }));
      setFollowUpOptions(options);
    });
  }, []);

  // 患者等级信息变更时
  useEffect(() => {
    const discount = levelInfo?.discount ?? 1.0;
    formRef.current?.setFieldsValue({
      discount_ratio: discount
    });
  }, [levelInfo]);

  useEffect(() => {
    const is_ballot = settleInfo.is_ballot === 'Y' ? true : false;
    // 结算信息有值，则填充数据
    const formData = {
      frank_name: settleInfo.frank_name,
      frank_phone: settleInfo.frank_phone,
      order_person: settleInfo.order_person,
      frank_address: settleInfo.frank_address,
      remarks: settleInfo.remarks,
      sec_remarks: settleInfo.sec_remarks,
      isShow: !isNull(settleInfo.survey_test_id) || !isNull(settleInfo.survey_date),
      survey_test_id: settleInfo.survey_test_id,
      survey_date: settleInfo.survey_date
    };
    if (!isNull(settleInfo.total_price)) {
      formRef.current?.setFieldsValue({
        ...formData,
        discount_ratio: settleInfo.discount_ratio,
        sett_price: settleInfo.sett_price,
        owing_price: settleInfo.owing_price,
        franking: settleInfo.franking,
        is_ballot
      });
    } else {
      // 默认把当前登录人名称填充到订单负责人
      formRef.current?.setFieldsValue({
        ...formData,
        order_person: initialState?.currentUser?.oper_name,
        is_ballot
      });
    }
    if (settleInfo.survey_date && moment().diff(moment(settleInfo.survey_date), 'seconds') >= 0) {
      setSurveyReadonly(true);
    } else {
      setSurveyReadonly(false);
    }
  }, [settleInfo]);

  useEffect(() => {
    if (goodsList.length) {
      let goodsNum1 = 0, goodsTotalPrice1 = 0, goodsDisaccountPrice1 = 0;
      goodsList.forEach(item => {
        if (item.goods_id) {
          goodsTotalPrice1 += Number(item.goods_total_price as number);
          setGoodsTotalPrice(parseFloat(goodsTotalPrice1).toFixed(2));

          goodsDisaccountPrice1 += Number(item.discount_price);
          setGoodsDisaccountPrice(parseFloat(goodsDisaccountPrice1).toFixed(2));

          goodsNum1 += item.goods_num as number;
          setGoodsNum(goodsNum1);
        }
      });
      const ratio = formRef.current?.getFieldValue('discount_ratio') || 1;
      const owing_price = formRef.current?.getFieldValue('owing_price') ?? 0;
      const franking = formRef.current?.getFieldValue('franking') ?? 0;
      // console.log('goodsDisaccountPrice1', ratio, goodsDisaccountPrice1, goodsList)
      // console.log('count', count)
      let val = Number(goodsDisaccountPrice1 * parseFloat(ratio));
      val = (val <= 0 ? 0.01 : val) - owing_price + franking;
      if (count > 0 || isNull(settleInfo.sett_price)) {
        formRef.current?.setFieldsValue({
          discount_ratio: ratio,
          sett_price: val.toFixed(2)
        });
      }
      setCount(count + 1)
    }
  }, [goodsList])

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    submit: () => {
      // formRef.current.submit();
      onSubmitForm('onSave', 'noBack');
    },
    clear: () => {
      formRef.current?.resetFields();
      setGoodsTotalPrice(0);
      setGoodsDisaccountPrice(0);
      setGoodsNum(0);
      setCount(0);
      formRef.current?.setFieldsValue({
        order_person: initialState?.currentUser?.oper_name,
      });
    }
  }))
  // console.log('initialState?.currentUser', initialState?.currentUser);

  // 保存订单/发起支付
  const onSubmitForm = async (type1: string, noBack = '') => {
    try {
      await formRef.current?.validateFields();
      const values = formRef.current?.getFieldsValue();
      const is_ballot = values.is_ballot === true ? 'Y' : 'N';
      const data = {
        ...values,
        survey_date: values.survey_date ? moment(values.survey_date).format('YYYYMMDD') : undefined,
        goods_total_price: goodsTotalPrice,
        total_price: goodsDisaccountPrice,
        service_price: 0,
        goodsNum,
        is_ballot
      }
      // 点击保存订单，一般停留在当前页
      if (type1 === 'onSave') {
        await onSave(data, 'onSave', noBack);
      } else {
        await onFinish(data, 'onPay');
      }

    } catch (error) {
      console.error(error);
    }
  }

  // 计算总额
  const priceCalc = () => {
    const ratio = formRef.current?.getFieldValue('discount_ratio') ?? 1;
    const owing_price = formRef.current?.getFieldValue('owing_price') ?? 0;
    const franking = formRef.current?.getFieldValue('franking') ?? 0;
    if (Number.isFinite(parseFloat(ratio)) && parseFloat(goodsDisaccountPrice) > 0) {
      let val = Number(goodsDisaccountPrice * ratio);
      val = (val <= 0 ? 0.01 : val) - owing_price + franking;
      formRef.current?.setFieldsValue({
        sett_price: val.toFixed(2)
      });
    }
  };

  // 判断开关是否需要打开
  const getIsShow = (...name: string[]) => {
    for (const nm of name) {
      if (!isNull(orderObj[nm])) {
        return true;
      }
    }
    return false;
  }

  const sn = initialState?.currentUser?.dept_type === 'Y' ? 5 : 3;

  return <div className="service-record">
    <div className="header">
      <div className="title" style={{ width: '100%' }}>{sn}.结算信息 {(isPay && type !== 'reopen') && <div style={{ float: 'right' }}><Badge status="success" text={<span style={{ fontSize: 12, color: '#52c41a' }}>已支付</span>} /></div>}</div>
    </div>
    <Divider style={{ margin: '10px 0' }} />

    <ProForm
      className="order-pro-form"
      formRef={formRef}
      scrollToFirstError
      submitter={{
        render: () => {
          return <div style={{ textAlign: 'right' }}>
            <PermissionControl action_id="400400001">
              <Button disabled={isPay && type !== 'reopen'} style={{ marginRight: 10 }} key="save" type="primary" onClick={async () => {
                onSubmitForm('onSave');
              }}>保存订单</Button>
            </PermissionControl>
            {
              !isMobile && <PermissionControl action_id="400400007">
                <Button disabled={isPay && type !== 'reopen'} key="pay" type="primary" onClick={async () => {
                  onSubmitForm('onPay');
                }}>发起支付</Button>
              </PermissionControl>
            }
          </div>
        }
      }}
      onFinish={async (values) => {
        onFinish(values, 'onPay');
      }}
      labelCol={{ flex: '0 0 90px' }}
      layout="horizontal"
    >
      <Row gutter={16} style={{ maxWidth: 1400 }}>
        <Col span={6}>
          <ProForm.Item label="商品原价">
            {goodsTotalPrice}（元）
          </ProForm.Item>
        </Col>
        <Col span={6}>
          <ProForm.Item label="商品数量">
            <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{goodsNum}</span>（件）
          </ProForm.Item>
        </Col>
        <Col span={6}>
          <ProForm.Item label="订单金额">
            {goodsDisaccountPrice} （元）
          </ProForm.Item>
        </Col>
        <Col span={6}>
          <ProFormDigit
            readonly={!initialState?.canDiscount}
            initialValue={1}
            rules={[
              { required: true },
              {
                validator: async (_, value) => value > 0 && value <= 1 ? Promise.resolve() : Promise.reject(new Error('订单折扣不能为0')),
                message: '订单折扣为0.01-1之间',
              }
            ]}
            fieldProps={{ precision: 2, onChange: priceCalc, onPressEnter: e => e.preventDefault() }}
            tooltip="如：9折输入0.9"
            label="订单折扣"
            name="discount_ratio"
          />
        </Col>
      </Row>
      <Row gutter={16} style={{ maxWidth: 1400 }}>
        <Col span={6}>
          <ProFormDigit label="欠款" name="owing_price"
            fieldProps={{ precision: 2, onChange: priceCalc, onPressEnter: e => e.preventDefault() }}
          />
        </Col>
        <Col span={6}>
          <ProFormDigit label="邮寄费用" name="franking"
            fieldProps={{
              precision: 2,
              onChange: priceCalc,
              onPressEnter: e => e.preventDefault()
            }}
          />
        </Col>
        <Col span={6}>
          <ProFormDigit
            readonly={!initialState?.canDiscount}
            rules={[
              { required: true, message: '请输入结算价格', },
              {
                validator: async (_, value) => value > 0 ? Promise.resolve() : Promise.reject(new Error('结算价格不能为0')),
                message: '结算价格不能为0',
              },
            ]}
            fieldProps={{
              precision: 2,
              formatter: value => !initialState?.canDiscount ? `${parseFloat(value || 0).toFixed(2)}（元）` : value,
              onChange: (value: number) => {
                if (Number.isFinite(parseFloat(value)) && parseFloat(goodsDisaccountPrice) > 0) {
                  let val = (value / goodsDisaccountPrice).toFixed(2);
                  val = parseFloat(val) <= 0 ? '0.01' : val;
                  formRef.current?.setFieldsValue({
                    discount_ratio: val,
                  })
                }
              },
              onBlur: (e: number) => {
                const value = e.target.value;
                if (Number.isFinite(parseFloat(value)) && parseFloat(goodsDisaccountPrice) > 0) {
                  let val = (value / goodsDisaccountPrice).toFixed(2);
                  val = parseFloat(val) <= 0 ? '0.01' : val;
                  formRef.current?.setFieldsValue({
                    discount_ratio: val,
                  })
                }
              },
              onPressEnter: e => e.preventDefault()
            }}
            label="结算价格"
            name="sett_price"
          />
        </Col>
        <Col span={6}>
          <ProFormCheckbox label="已开具发票" name="is_ballot" />
        </Col>
      </Row>
      <Row gutter={16} style={{ maxWidth: 1400 }}>
        <Col span={6}>
          <ProFormText label="收件人" name="frank_name" />
        </Col>
        <Col span={6}>
          <ProFormText label="收件人电话" name="frank_phone" />
        </Col>
        <Col span={6}>
          <ProFormText label="订单负责人" name="order_person" />
        </Col>
      </Row>

      <Row style={{ maxWidth: 1400 }} gutter={16}>
        <Col span={21}>
          <ProFormText label="收件地址" name="frank_address" />
        </Col>
      </Row>
      <Row style={{ maxWidth: 1400 }} gutter={16}>
        <Col span={21}>
          <ProFormText label="订单备注1" name="remarks" />
        </Col>
      </Row>
      <Row style={{ maxWidth: 1400 }} gutter={16}>
        <Col span={21}>
          <ProFormText label="订单备注2" name="sec_remarks" />
        </Col>
      </Row>

      {
        initialState?.currentUser?.dept_type === 'Y' &&
        <div style={{ padding: '10px 0' }}>
          <div className="header">
            <div className="title" style={{ width: '100%' }}>{sn + 1}.患者随访</div>
            <ProFormSwitch name="isShow" />
          </div>
          <Divider style={{ margin: '10px 0' }} />
          {
            // 随访信息
            <ProFormDependency name={['isShow']}>
              {({ isShow }) => (
                isShow ? (
                  <Row style={{ width: 1000 }} gutter={24}>
                    <Col span={8}>
                      <ProFormSelect
                        label="随访调研表" name="survey_test_id"
                        options={followUpOptions} readonly={surveyReadonly}
                        required rules={[{ required: true }]} fieldProps={{ size: 'small' }} />
                    </Col>
                    <Col span={8}>
                      <ProFormDatePicker
                        label="随访日期" name="survey_date"
                        required rules={[{ required: true }]} readonly={surveyReadonly}
                        fieldProps={{ style: { width: '100%' }, format: 'YYYY-MM-DD', disabledDate: current => (current && current < moment().endOf("day")) }}
                      />
                    </Col>
                  </Row>

                ) : null
              )}
            </ProFormDependency>
          }
        </div>
      }
    </ProForm>
  </div >
});
export default SettlementInfo;
